import { HttpCode } from "@/enums/httpEnum";
import { HttpReqContentType } from "@/enums/httpEnum";
// * http quest
import axios, { AxiosError, AxiosRequestConfig, AxiosResponse } from "axios";
import { useUserStore } from "@/store/index";
import { message } from "antd";

// response data type
interface ResObject<T> {
  code: HttpCode;
  msg?: string;
  data: T;
}

// * axios
const service = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  timeout: import.meta.env.VITE_REQUEST_TIMEOUT,
  headers: { ContentType: HttpReqContentType.JSON },
});

service.interceptors.request.use(
  (config) => {
    const token = useUserStore.getState().token;
    if (token) {
      config.headers.Authorization = token;
    }
    return config;
  },
  (error: AxiosError) => {
    return Promise.reject(error);
  }
);

const request = async <T>($config: AxiosRequestConfig): Promise<T> => {
  return service
    .request<ResObject<T>>($config)
    .then((data) => {
      const { code, msg, data: $data } = data.data;
      if (code !== HttpCode.SUCCESS) {
        if (msg) message.error(msg);
        return Promise.reject();
      }
      if (msg) message.success(msg);
      return $data;
    })
    .catch((e) => {
      return Promise.reject(e);
    });
};

export default request;
